package com.citsin.atlas.fragment

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.citsin.atlas.R
import com.citsin.atlas.adapter.MediaPreviewAdapter
import com.citsin.atlas.viewmodel.MediaViewModel
import com.citsin.atlas.viewmodel.MediaViewModelProviderFactory
import kotlinx.android.synthetic.main.fragment_preview.*

/**
 * citsin
 * 2019-06-04
 */
class PreviewFragment : Fragment() {

    private lateinit var mViewModel: MediaViewModel
    private lateinit var mAdapter: MediaPreviewAdapter

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mAdapter = MediaPreviewAdapter()
        val types = arguments!!.getIntArray("types")!!.toTypedArray()
        val id = arguments!!.getString("id")
        val factory = MediaViewModelProviderFactory(requireActivity().application, types, id!!)
        mViewModel = ViewModelProvider(this, factory).get(MediaViewModel::class.java)
        mViewModel.getMedia().observe(this, Observer { medias ->
            mAdapter.submitList(medias)
            viewPager.setCurrentItem(arguments!!.getInt("pos", 0), false)
        })
    }


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_preview, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewPager.adapter = mAdapter
    }
}
